<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/3/3
 * Time: 17:38
 */

namespace App\Http\Logics;

use App\Common;
use App\DynamicVideo;
use App\PartyContent;
use App\ProductContent;
use App\SystemNotifyContent;
use App\TrainContent;
use App\Video;
use Illuminate\Support\Facades\Redis;
use QCloud\Cos\Api;
class CommonLogic extends BaseLogic
{
    const DYNAMIC_VIDEO = 'dynamic_video';
    const PARTY_CONTENT_VIDEO = 'party_content';
    const TRAIN_CONTNT_VIDEO = 'train_content';
    const SYSTEM_NOTIFY_CONTENT_VIDEO = 'system_notify_content';
    const PRODUCT_CONTENT_VIDEO = 'product_content';
    const NORMAL_VIDEO = 'video';
    public static function createReusableSignature($data)
    {
        $config = array(
            'app_id' => '1253709024',
            'secret_id' => 'AKIDvkT2ResaddffU7Jr0zmOp6CC2JZl6958',
            'secret_key' => '3vrt1HPLCwp0406Meoo1c7nqxmS6Zs17',
            'region' => $data['region'],   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
            'timeout' => 60
        );
        date_default_timezone_set('PRC');
        $cosApi = new Api($config);
        // 获取签名
        $ret = $cosApi->getReusableSignature($data['bucket']);
        return self::response(self::SUCCESS, $ret);
    }

    /**
     * 缓存视频信息
     * @param $data
     * @return bool
     */
    public static function cacheVideoInfo($data)
    {
        if (empty(Redis::get($data['key']))){
            Redis::set($data['key'], $data['value']);
            return true;
        }else{
            Redis::del($data['key']);
            return false;
        }
    }

    public static function callback($data)
    {
        $result = array();
        preg_match_all("/(?:__)(.*)(?:__)/i",$data['cover_url'], $result);
        if (empty(Redis::get($data['cover_url']))){
            Redis::set($data['cover_url'], $result[1][0]);
            Redis::set($data['cover_url'].'-height', $data['height']);
            Redis::set($data['cover_url'].'-width', $data['width']);
        }else{
            $type = $result[1][0];
            switch ($type){
                case CommonLogic::DYNAMIC_VIDEO:
                    $dynamic_video = DynamicVideo::where('cover', $data['cover_url'])->first();
                    $dynamic_video->height = $data['height'];
                    $dynamic_video->width = $data['width'];
                    $dynamic_video->is_transcode = DynamicVideo::TRANSCODE;
                    if (!$dynamic_video->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                case CommonLogic::PARTY_CONTENT_VIDEO:
                    $party_content = PartyContent::where('video_cover', $data['cover_url'])->first();
                    $party_content->video_height = $data['height'];
                    $party_content->video_width = $data['width'];
                    $party_content->is_transcode = DynamicVideo::TRANSCODE;
                    if (!$party_content->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                case CommonLogic::TRAIN_CONTNT_VIDEO:
                    $train_content = TrainContent::where('video_cover', $data['cover_url'])->first();
                    $train_content->video_height = $data['height'];
                    $train_content->video_width = $data['width'];
                    $train_content->is_transcode = DynamicVideo::TRANSCODE;
                    if (!$train_content->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                case CommonLogic::SYSTEM_NOTIFY_CONTENT_VIDEO:
                    $train_content = SystemNotifyContent::where('video_cover', $data['cover_url'])->first();
                    $train_content->video_height = $data['height'];
                    $train_content->video_width = $data['width'];
                    $train_content->is_transcode = DynamicVideo::TRANSCODE;
                    if (!$train_content->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                case CommonLogic::PRODUCT_CONTENT_VIDEO:
                    $train_content = ProductContent::where('video_cover', $data['cover_url'])->first();
                    $train_content->video_height = $data['height'];
                    $train_content->video_width = $data['width'];
                    $train_content->is_transcode = DynamicVideo::TRANSCODE;
                    if (!$train_content->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                case CommonLogic::NORMAL_VIDEO:
                    $video = Video::where('cover', $data['cover_url'])->first();
                    $video->height = $data['height'];
                    $video->width = $data['width'];
                    $video->is_transcode = Video::TRANSCODE;
                    if (!$video->save()){
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                    Redis::del($data['cover_url']);
                    break;
                default:
                    break;
            }
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 图文处理
     * @param $system_notify_content
     * @param $item
     * @return mixed
     */
    public static function handleContent($obj, $item)
    {
        $obj->type = $item->type;

        switch ($item->type){
            case Common::TEXT:
                $obj->text = nl2br($item->text);
                if (!$obj->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                break;
            case Common::PHOTO:
                $obj->photo_url = $item->photo_url;
                $url = $item->photo_url . "?imageInfo";
                // 处理图片
                $rs = dealHttp($url);
                $width = $rs->width;
                $height = $rs->height;
                $obj->photo_width = $width;
                $obj->photo_height = $height;
                if (!$obj->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                break;
            case Common::VIDEO:
                $obj->video_url = $item->video_url;
                $obj->video_cover = $item->video_url.'.0_0.p0.jpg';
                // 判断视频是否转码
                $data_two = [
                    'key' => $obj->video_cover,
                    'value' => 'party_content'
                ];
                if (!self::cacheVideoInfo($data_two)){
                    if (Redis::get($obj->video_cover.'-height') && Redis::get($obj->video_cover.'-width')){
                        $obj->video_height = Redis::get($obj->video_cover.'-height');
                        $obj->video_width = Redis::get($obj->video_cover.'-width');
                        $obj->is_transcode = SystemNotifyContent::TRANSCODE;
                        Redis::del($obj->cover.'-height');
                        Redis::del($obj->cover.'-widht');
                    }
                }
                if (!$obj->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                break;
            case Common::ADDRESS:
                $obj->address = $item->address;
                $obj->address_name = $item->address_name;
                $obj->lat = $item->lat;
                $obj->lng = $item->lng;
                if (!$obj->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                break;
            default:
                break;
        }
        return self::response(self::SUCCESS);
    }


    public static function uploadPhoto($data)
    {
        try{
            $url = uploadImage(storage_path().'/app/'.$data['photo_file'], 'photos');
            if($fp = fopen(storage_path().'/app/'.$data['photo_file'],"rb", 0))
            {
                $gambar = fread($fp,filesize(storage_path().'/app/'.$data['photo_file']));
                fclose($fp);


                $base64 = chunk_split(base64_encode($gambar));
            }
            $arr = [
                'file' => 'data:image/jpg/png/gif;base64,'.$base64,
                'url' => $url
            ];
            return self::response(self::SUCCESS, $arr);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getImageInfo($data)
    {
        errorLog($data);
        $url = $data['url'] . "?imageInfo";
        // 处理图片
        $rs = dealHttp($url);
        $width = $rs->width;
        $height = $rs->height;
        $image_info = [
            'width' => $width,
            'height' => $height
        ];
        return self::response(self::SUCCESS, $image_info);
    }
}